/**
 * 音频格式转换工具
 * 用于将录制的音频转换为后端支持的格式
 */

/**
 * 将音频Blob转换为WAV格式
 * @param audioBlob 原始音频Blob
 * @returns 转换后的WAV格式Blob
 */
export async function convertToWav(audioBlob: Blob): Promise<Blob> {
  return new Promise((resolve, reject) => {
    const audioContext = new (window.AudioContext || (window as any).webkitAudioContext)();
    const fileReader = new FileReader();

    fileReader.onload = async (e) => {
      try {
        const arrayBuffer = e.target?.result as ArrayBuffer;
        const audioBuffer = await audioContext.decodeAudioData(arrayBuffer);
        
        // 转换为WAV格式
        const wavBlob = audioBufferToWav(audioBuffer);
        resolve(wavBlob);
      } catch (error) {
        reject(error);
      }
    };

    fileReader.onerror = () => reject(new Error('文件读取失败'));
    fileReader.readAsArrayBuffer(audioBlob);
  });
}

/**
 * 将AudioBuffer转换为WAV格式的Blob
 * @param audioBuffer 音频缓冲区
 * @returns WAV格式的Blob
 */
function audioBufferToWav(audioBuffer: AudioBuffer): Blob {
  const numberOfChannels = audioBuffer.numberOfChannels;
  const sampleRate = audioBuffer.sampleRate;
  const format = 1; // PCM
  const bitDepth = 16;

  const bytesPerSample = bitDepth / 8;
  const blockAlign = numberOfChannels * bytesPerSample;
  const byteRate = sampleRate * blockAlign;
  const dataSize = audioBuffer.length * blockAlign;
  const bufferSize = 44 + dataSize;

  const arrayBuffer = new ArrayBuffer(bufferSize);
  const view = new DataView(arrayBuffer);

  // WAV文件头
  const writeString = (offset: number, string: string) => {
    for (let i = 0; i < string.length; i++) {
      view.setUint8(offset + i, string.charCodeAt(i));
    }
  };

  // RIFF chunk descriptor
  writeString(0, 'RIFF');
  view.setUint32(4, bufferSize - 8, true);
  writeString(8, 'WAVE');

  // FMT sub-chunk
  writeString(12, 'fmt ');
  view.setUint32(16, 16, true); // Sub-chunk size
  view.setUint16(20, format, true); // Audio format
  view.setUint16(22, numberOfChannels, true); // Number of channels
  view.setUint32(24, sampleRate, true); // Sample rate
  view.setUint32(28, byteRate, true); // Byte rate
  view.setUint16(32, blockAlign, true); // Block align
  view.setUint16(34, bitDepth, true); // Bits per sample

  // Data sub-chunk
  writeString(36, 'data');
  view.setUint32(40, dataSize, true);

  // 写入音频数据
  let offset = 44;
  for (let channel = 0; channel < numberOfChannels; channel++) {
    const channelData = audioBuffer.getChannelData(channel);
    for (let i = 0; i < channelData.length; i++) {
      const sample = Math.max(-1, Math.min(1, channelData[i]));
      const intSample = sample < 0 ? sample * 0x8000 : sample * 0x7FFF;
      view.setInt16(offset, intSample, true);
      offset += 2;
    }
  }

  return new Blob([arrayBuffer], { type: 'audio/wav' });
}

/**
 * 检查浏览器支持的录音格式，优先返回后端支持的格式
 * @returns 支持的MIME类型和对应的文件扩展名
 */
export function getSupportedAudioFormat(): { mimeType: string; extension: string } {
  // 后端支持的格式，按优先级排序
  const backendSupportedFormats = [
    { mimeType: 'audio/mp4', extension: 'mp4' },
    { mimeType: 'audio/mpeg', extension: 'mp3' },
    { mimeType: 'audio/wav', extension: 'wav' },
    { mimeType: 'audio/wave', extension: 'wav' },
    { mimeType: 'audio/m4a', extension: 'm4a' },
    { mimeType: 'audio/x-m4a', extension: 'm4a' }
  ];

  // 检查浏览器支持的格式
  for (const format of backendSupportedFormats) {
    if (MediaRecorder.isTypeSupported(format.mimeType)) {
      console.log('✅ 找到支持的格式:', format);
      return format;
    }
  }

  // 如果都不支持，返回最通用的格式，后续需要转换
  console.log('⚠️ 浏览器不支持后端要求的格式，将使用WebM录制后转换');
  return { mimeType: 'audio/webm', extension: 'webm' };
}

/**
 * 确保音频格式符合后端要求
 * @param audioBlob 原始音频Blob
 * @param originalExtension 原始文件扩展名
 * @returns 符合后端要求的音频Blob和文件扩展名
 */
export async function ensureCompatibleFormat(
  audioBlob: Blob, 
  originalExtension: string
): Promise<{ blob: Blob; extension: string }> {
  
  const backendSupportedTypes = [
    'audio/mp3', 'audio/mpeg', 'audio/wav', 'audio/wave', 
    'audio/m4a', 'audio/x-m4a', 'audio/mp4'
  ];

  // 如果已经是支持的格式，直接返回
  if (backendSupportedTypes.includes(audioBlob.type)) {
    console.log('✅ 音频格式已符合后端要求:', audioBlob.type);
    return { blob: audioBlob, extension: originalExtension };
  }

  // 需要转换为WAV格式
  console.log('🔄 转换音频格式:', audioBlob.type, '→ audio/wav');
  
  try {
    const wavBlob = await convertToWav(audioBlob);
    console.log('✅ 音频格式转换成功');
    return { blob: wavBlob, extension: 'wav' };
  } catch (error) {
    console.error('❌ 音频格式转换失败:', error);
    
    // 转换失败，创建一个WAV格式的Blob（即使内容可能不兼容）
    const compatibleBlob = new Blob([audioBlob], { type: 'audio/wav' });
    return { blob: compatibleBlob, extension: 'wav' };
  }
}

/**
 * 获取音频文件的扩展名
 * @param mimeType MIME类型
 * @returns 文件扩展名
 */
export function getExtensionFromMimeType(mimeType: string): string {
  const mimeToExtension: Record<string, string> = {
    'audio/mp3': 'mp3',
    'audio/mpeg': 'mp3',
    'audio/wav': 'wav',
    'audio/wave': 'wav',
    'audio/m4a': 'm4a',
    'audio/x-m4a': 'm4a',
    'audio/mp4': 'mp4',
    'audio/webm': 'webm',
    'audio/ogg': 'ogg'
  };

  return mimeToExtension[mimeType] || 'wav';
}
